package com.lq.whattoeattoday.util;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.lq.whattoeattoday.Enum.TypeEnum;
import com.lq.whattoeattoday.config.SizeConfig;
import com.lq.whattoeattoday.pojo.FoodPojo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.swing.*;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author 15784
 */
@Component
@Slf4j
public class FoodUtil
{

    @Resource
    private SizeConfig sizeUtil;


    /**
     * 获取今天吃啥的菜品信息
     *
     * @param type   类型
     * @param openId 用户唯一标识
     * @return
     */
    public FoodPojo getRandomFood(Integer type, String openId)
    {
        String beanName = TypeEnum.getTypeName(type);
        JSONArray jsonArray = SpringUtil.getBean(beanName, JSONArray.class);
        int sizeMax = jsonArray.size();
        Integer index = selectRandomDish(openId, sizeMax);
        JSONObject object = jsonArray.getJSONObject(index);
        return object.toBean(FoodPojo.class);
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    public Integer selectRandomDish(String openid, Integer totalCandidates)
    {
        String bitmapKey = getBitmapKey(openid);
        int selectedIndex = 0;

        //判断是否全部已经抽取过了
        long size = countKeysWithPrefix(bitmapKey);
        if (size == totalCandidates)
        {
            log.info("近15天内所有候选菜品都已被选择过，需要采取其他策略。");
            return null;
        }

        Boolean lastSevenDaysBits;
        //判断当前索引是否已经被抽取过
        do
        {
            selectedIndex = (int) (Math.random() * totalCandidates);
            lastSevenDaysBits = redisTemplate.opsForValue().getBit(bitmapKey, selectedIndex);
        } while (Boolean.TRUE.equals(lastSevenDaysBits));

        // 将索引标记为已抽取
        redisTemplate.opsForValue().setBit(bitmapKey, selectedIndex, true);
        redisTemplate.expire(bitmapKey, 15, TimeUnit.DAYS);
        //  redisTemplate.expire(bitmapKey, 10, TimeUnit.SECONDS);
        return selectedIndex;
    }

    public long countKeysWithPrefix(String prefix)
    {
        Set<String> keys = redisTemplate.keys(prefix + "*");
        assert keys != null;
        return keys.size();
    }

    private String getBitmapKey(String openid)
    {
        return "bitmap:" + openid;
    }


}
